<template>
  <div>
    <div class="add-smoothie container">
      <h2 class="center-align indigo-text">Add New Smoothie Recipe</h2>
      <form @submit.prevent="AddSmoothie">
        <div class="field title">
          <label for="title">Smoothie Title</label>
          <input type="text" name="title" v-model="title" />
        </div>
        <div class="field ingredient" v-for="(ing,index) in ingredients" :key="index">
          <label for="ingredient">Ingredient</label>
          <input type="text" name="ingredient" v-model="ingredients[index]" />
          <i class="material-icons delete" @click="deleteIng(index)">delete</i>
        </div>
        <div class="field add-ingredient">
          <label for="add-ingredient">Add an ingredient</label>
          <input type="text" name="add-ingredient" @keydown.tab.prevent="AddIng" v-model="another" />
        </div>
        <div class="field center-align">
          <p if="feedback" class="red-text">{{feedback}}</p>
          <button class="btn pink">Add Smoothie</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import db from "@/firebase/init";
import slugify from "slugify";

export default {
  name: "AddSmoothie",
  data() {
    return {
      title: null,
      another: null,
      ingredients: [],
      feedback: null,
      slug: null
    };
  },
  methods: {
    AddSmoothie() {
      //console.log(this.title,this.ingredients)
      if (this.title) {
        this.feedback = null;
        this.slug = slugify(this.title, {
          replacement: "-",
          remove: /[$*_+~.()'"!\-:@]/g,
          lower: true
        });
        //console.log(this.slug);
        let ingredientsAdd = [...this.ingredients, this.another];
        db.collection("smoothies")
          .add({
            title: this.title,
            ingredients: ingredientsAdd.filter(
              ing => ing !== null && ing.length > 0
            ),
            slug: this.slug
          })
          .then(() => {
            this.$router.push({ name: "Index" });
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        this.feedback = "You must endter a smoothie title";
      }
    },
    AddIng() {
      if (this.another) {
        this.ingredients.push(this.another);
        this.another = null;
        this.feedback = null;
        //console.log(this.ingredients)
      } else {
        this.feedback = "You must enter a value";
      }
    },
    deleteIng(index) {
      this.ingredients = this.ingredients.filter(
        (ing, argIndex) => argIndex !== index
      );
    }
  }
};
</script>

<style>
.add-smoothie {
  margin-top: 60px;
  padding: 20px;
  max-width: 500px;
}
.add-smoothie h2 {
  font-size: 2em;
  margin: 20px auto;
}
.add-smoothie .field {
  margin: 20px auto;
  position: relative;
}
.add-smoothie .delete {
  position: absolute;
  right: 0;
  bottom: 16px;
  color: #aaa;
  font-size: 1.4em;
  cursor: pointer;
}
</style>